package mongodb

import (
	"context"
	"fmt"
	"github.com/pingcap/errors"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"net/url"
)

func AsyncSaveMessage(ctx context.Context, client *mongo.Client, database string, collection string, message *MongoMessage) error {
	// 检查集合database是否存在
	// 检查集合是否存在，如果不存在需要创建集合、索引、ttl等
	db := client.Database(database)
	if db == nil {
		return errors.New("mongo open database fail")
	}

	exists, err := CheckCollectionExists(ctx, db, collection)
	if err != nil {
		return err
	}

	if exists == false {
		// 创建集合、索引、ttl
		indexModels := []mongo.IndexModel{
			{
				Keys:    bson.D{{"createat", 1}},
				Options: options.Index().SetExpireAfterSeconds(24 * 60 * 60), //1day
			},
			{
				Keys:    bson.D{{"ts", 1}},
				Options: options.Index().SetUnique(true),
			},
		}

		_, err = db.Collection(collection).Indexes().CreateMany(ctx, indexModels)
		if err != nil {
			return err
		}
	}

	_, err = db.Collection(collection).InsertOne(ctx, message)
	if err != nil {
		return err
	}

	return nil
}

func CheckCollectionExists(ctx context.Context, database *mongo.Database, collection string) (bool, error) {
	filter := bson.M{"name": bson.M{"$regex": "^" + collection}}
	names, err := database.ListCollectionNames(ctx, filter)
	if err != nil {
		return false, err
	}

	if names != nil && len(names) > 0 {
		return true, nil
	}

	return false, nil
}

func CheckSinkURI(sinkURI *url.URL) error {
	if sinkURI.Scheme == "" {
		return fmt.Errorf("scheme is empty")
	}
	if sinkURI.Host == "" {
		return fmt.Errorf("host is empty")
	}
	if sinkURI.Path == "" {
		return fmt.Errorf("path is empty")
	}
	return nil
}
